//
//  HLHomeController.swift
//  HLwWeibo
//
//  Created by hqhxu on 16/2/26.
//  Copyright © 2016年 hqhxu. All rights reserved.
//


import UIKit

import SVPullToRefresh //上拉加载跟多 第三方

class HLHomeController: HLBaseTableViewController {

private let reusaIdentifier = "cell"
    
    /// 微博数组
    var statusesData:[HLStatuses]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        //如果没有登录就不要去设置导航栏、加载数据
        if  !HLAccountViewModel.shareInstance.userLogin {
            return
        }
        
        tableView.estimatedRowHeight = 150
        tableView.rowHeight = UITableViewAutomaticDimension
        
        // 添加导航浪上的按钮
        addNagationmIte()
        
       // 加载用户头像
        HLAccountViewModel.shareInstance.loadUserInform { (error) -> () in
            
            if error == nil {
                self.titleView.setTitle(HLAccountViewModel.shareInstance.userAcount?.screen_name, forState: UIControlState.Normal)
                
                self.titleView.sizeToFit()
            }
        }
        
        prepareUI()
}
    
    /// 实现下拉刷新 上拉加载更多
    private func prepareUI() {
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.allowsSelection = false
        // 添加下拉刷新控件
        self.refreshControl = HLRefreshControl()
        
        self.refreshControl?.addTarget(self, action: "loadNewStatuses", forControlEvents: UIControlEvents.ValueChanged)
        
        // 开始进入的时候让它自动刷星数据
        self.refreshControl?.beginRefreshing()
        refreshControl?.sendActionsForControlEvents(UIControlEvents.ValueChanged)
        
        
        //上拉加载更多
        tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            //上拉加载跟多
            self.loadMareStatuses()
        }
    }
    
    /// 上拉加载更多
    func loadMareStatuses() {
        let max_id = statusesData?.last?.id ?? 0
        
        if max_id == 0 {
            return
        }
        
        HLStatusesViewModel.shareInstance.loadStatuses(nil, max_id: max_id) { (statuses, error) -> () in
            
            self.tableView.infiniteScrollingView.stopAnimating()
            
            if error != nil {
                print("加载更多微博数据时出错了error:\(error)")
                return
            }
            
            if let count = statuses?.count where count > 0 {
                
                self.statusesData = self.statusesData! + statuses!
            }

        }
        
    }
    /// 加载新微博数据
    func loadNewStatuses() {
        
        // 没有就给0
        let since_id = statusesData?.first?.id ?? 0
        // 加载微博数据
        HLStatusesViewModel.shareInstance.loadStatuses(since_id, max_id: nil) { (statuses, error) -> () in
            /// 刷新完成后不管是加载到了新数据还是没有加载到新数据都结束刷新控件
            self.refreshControl?.endRefreshing()
//            self.refreshControl.
            
            if error != nil {
                print("加载微博数据出错:\(error)")
                return
            }
            
            let count = statuses?.count ?? 0
            
            if since_id > 0 {
                //在这里添加下拉刷新的提示
                self.ShowTipView(count)
            }
            
            if count == 0 { //没有加载到数据
                return
            }
            
            if since_id == 0 { // 第一次加载
                self.statusesData = statuses
            }else {
                
                // 可以在这之前把图片的url转为图片
                self.statusesData = statuses! + self.statusesData!
                print("我在控制器home中获得了微博数据:\(statuses)")
                
            }
        }
    }
    
    lazy var tipLable:UILabel = {
        let label = UILabel(textColor: UIColor.whiteColor(), font: 14)
        label.backgroundColor = UIColor.orangeColor()
        
        label.sizeToFit()
        
        label.textAlignment = NSTextAlignment.Center
//        label.contentMode = UIViewContentMode.Center
        
        return label
    }()
    
    ///显示新加载的微博数据提示
    func ShowTipView(count:Int) {
        
        let navigationBar = self.navigationController!.navigationBar
        
        navigationBar.insertSubview(tipLable, atIndex: 0)
        
        tipLable.text = "加载了新微博\(count)条"
        
        tipLable.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(navigationBar.snp_bottom)
            
            make.leading.trailing.equalTo(navigationBar)
            
            make.height.equalTo(44)
        }
        
        //实现动画
        UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
            
            self.tipLable.frame.origin.y = 44
            
            }) { (_) -> Void in
                UIView.animateWithDuration(0.5, delay: 1, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    
                    self.tipLable.frame.origin.y = -44-22
                    
                    }, completion: { (_) -> Void in
                })
        }
    }
    
    func addNagationmIte() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftItem)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightItem)
        
        navigationItem.titleView = titleView
        
    }
    
    // 点击了中间的头像按钮
    func didClickTitleButton(button:HLCoustomButton) {
        
        button.selected = !button.selected
        //执行动画
        UIView.animateWithDuration(0.25) { () -> Void in
            if button.selected == true {
                /*
                uiview动画会自动判断 只会往角度小的方向转  
                uiview动画如果旋转360度不会动
                */
                button.imageView!.transform = CGAffineTransformMakeRotation(CGFloat(M_PI - 0.0001))
                //弹出popover视图
                self.presentPopoverView()
                
            }else {
                button.imageView!.transform = CGAffineTransformIdentity
            }
        }
    }
    
    //显示popoer视图
    private func presentPopoverView() {
        
        let PopoverVC = HLPopoverController()
        //设置弹出模式
        PopoverVC.modalPresentationStyle = UIModalPresentationStyle.Popover
        //设置弹出大小和跟随的view
        let button = navigationItem.titleView as! HLCoustomButton
        PopoverVC.popoverPresentationController?.sourceView = button
        PopoverVC.popoverPresentationController?.sourceRect = button.bounds
        
        // 设置代理
        PopoverVC.popoverPresentationController?.delegate = self
        
        PopoverVC.preferredContentSize = CGSizeMake(200, 44*5)
        
        presentViewController(PopoverVC, animated: true, completion: nil)
        
    }
    
    // MARK:- 懒加载
    private lazy  var leftItem:UIButton = {
        let button = UIButton(type: UIButtonType.Custom)
        
        button.setBackgroundImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
        button.sizeToFit()
        
        return button
    }()
    
    private lazy var titleView:UIButton = {
        let button = HLCoustomButton(type: UIButtonType.Custom)
        
        button.setTitle("首页", forState: UIControlState.Normal)
        button.setImage(UIImage(named: "navigationbar_arrow_down") , forState: UIControlState.Normal)
        button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        
        button.addTarget(self, action: "didClickTitleButton:", forControlEvents: UIControlEvents.TouchUpInside)
//        button.sizeToFit()
        
        return button
    }()
    
    private  var rightItem:UIButton = {
        let button = UIButton(type: UIButtonType.Custom)
        
        button.setBackgroundImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
        button.sizeToFit()
        
        return button
    }()

}

extension HLHomeController:UIPopoverPresentationControllerDelegate {
    
    /// popoVer的代理方法  不需要自动适配大小
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.None
    }
    
    /// 当popoVer要消失的时候调用
    func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
        
        let button = navigationItem.titleView as! HLCoustomButton
            
        didClickTitleButton(button)
    }
}

// MARK: - UITableViewDatasource  UITableViewdelegate
extension HLHomeController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        // 注意问号一定得隔开
        return statusesData?.count ?? 0
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCellWithIdentifier(reusaIdentifier) as? HLStatuseCell
        
        if cell == nil {
            cell = HLStatuseCell(style: UITableViewCellStyle.Default, reuseIdentifier: reusaIdentifier)
        }
        // 给cell的微博模型赋值
        cell?.statuses = self.statusesData?[indexPath.row]
        
        return cell!
    }

//    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
//        return false
//    }
    
//    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//        
//        tableView.deselectRowAtIndexPath(indexPath, animated: false)
//    }
}
